class SimpleVM:
    def __init__(self):
        self.stack = []
        self.locals = {}
        self.globals = {}

    def load_const(self, const):
        self.stack.append(const)
        print(f'加载常量到{const}到栈中')

    def store_name(self, name):
        if not self.stack:
            raise RuntimeError('栈为空')
        # 取出栈顶的元素
        value = self.stack.pop()
        self.locals[name] = value
    
    def load_name(self, name):
        if name in self.locals:
            value = self.locals[name]
        elif name in self.globals:
            value = self.globals[name]
        else:
            raise NameError(f'name {name} is not defined')
        self.stack.append(value)

    def binary_add(self):
        if len(self.stack) < 2:
            raise RuntimeError("栈中的元素不足")
        b = self.stack.pop()
        a = self.stack.pop()
        result = a + b
        self.stack.append(result)

    def return_value(self):
        if not self.stack:
            return None
        value = self.stack.pop()
        return value
    

def vm_execution():
    vm = SimpleVM()
    print('执行代码: a=10;b=20;c=a+b')
    instructions = [
        #  这是元组类型，元组就是不可变数组，这个JS里没有，但是python是有的
        ("LOAD_CONST", 10),  # 加载常量10
        ("STORE_NAME", "a"),  # 存储到变量a
        ("LOAD_CONST", 20),  # 加载常量20
        ("STORE_NAME", "b"),  # 存储到变量b
        ("LOAD_NAME", "a"),  # 加载变量a
        ("LOAD_NAME", "b"),  # 加载变量b
        ("BINARY_ADD",),  # 执行加法
        ("STORE_NAME", "c"),  # 存储到变量c
        ("LOAD_NAME", "c"),  # 加载变量c
        ("RETURN_VALUE",),  # 返回值
    ]
    for instruction in instructions:
        op = instruction[0]
        # [索引:结束:步长]
        args = instruction[1:] if len(instruction) > 1 else ()
        if op == 'LOAD_CONST':
            vm.load_const(args[0])
        elif op == 'STORE_NAME':
            vm.store_name(args[0])
        elif op == 'LOAD_NAME':
            vm.load_name(args[0])
        elif op == 'BINARY_ADD':
            vm.binary_add()
        elif op == 'RETURN_VALUE':
            result = vm.return_value()
            break
    print('111111111111111111')
    print(f'最终结果是: {result}')
vm_execution()





